package cn.rui.service.exam;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.rui.common.ContentBean;
import cn.rui.common.ResponseBean;
import cn.rui.mapper.UserMapper;
import cn.rui.mapper.exam.*;
import cn.rui.pojo.User;
import cn.rui.pojo.exam.ExamQuestion;
import cn.rui.pojo.exam.Paper;
import cn.rui.pojo.exam.UserAnswer;
import cn.rui.pojo.vo.PageVo;
import cn.rui.pojo.vo.QuestionIdAndAnswer;
import cn.rui.pojo.vo.TestExamAnswerVo;
import cn.rui.pojo.vo.UserAnswerDetail;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @author 徽州大都督
 * @date 2021/6/28
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserAnswerService {

    @Autowired
    private UserAnswerMapper userAnswerMapper;
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private PaperMapper paperMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RandomPaperQuestionMapper randomPaperQuestionMapper;
    @Autowired
    private ManualPaperQuestionMapper manualPaperQuestionMapper;

    public ResponseBean save(TestExamAnswerVo testExamAnswerVo) {

        String username = testExamAnswerVo.getUsername ();
        QueryWrapper<User> wrapper = new QueryWrapper<> ();
        wrapper.eq ("username", username);
        User user = userMapper.selectOne (wrapper);

        //判断该用户是否已提交过试卷
        QueryWrapper<UserAnswer> wrapper1 = new QueryWrapper<> ();
        wrapper1.eq ("user_id", user.getId ());
        wrapper1.eq ("paper_id", testExamAnswerVo.getPaperId ());
        UserAnswer userAnswer1 = userAnswerMapper.selectOne (wrapper1);
        if (ObjectUtil.isNotNull (userAnswer1)) {
            return ResponseBean.error ("请勿重复提交试卷");
        }

        UserAnswer userAnswer = new UserAnswer ();
        userAnswer.setUserId (user.getId ());
        userAnswer.setPaperId (testExamAnswerVo.getPaperId ());
        //主观题得分
        Integer subjectiveScore = 0;
        Paper paper = paperMapper.selectById (testExamAnswerVo.getPaperId ());
        //单选题答案计算
        //System.out.println ("单选题答案"+testExamAnswerVo.getRadioList ());
        if (CollUtil.isNotEmpty (testExamAnswerVo.getRadioList ())) {
            List<QuestionIdAndAnswer> radioList = testExamAnswerVo.getRadioList ();
            List<String> radioAnswer = new ArrayList<> ();
            for (QuestionIdAndAnswer questionIdAndAnswer : radioList) {
                ExamQuestion examQuestion = questionMapper.selectById (questionIdAndAnswer.getQuestionId ());
                String radio = questionIdAndAnswer.getQuestionId () + "-" + questionIdAndAnswer.getAnswer ();
                radioAnswer.add (radio);
                if (examQuestion.getRadioAnswer ().trim ().equals (questionIdAndAnswer.getAnswer ())) {
                    subjectiveScore += paper.getRadioScore ();
                }
            }
            //String转List
//            String str = "a,b,c";
//            List<String> list1 = Arrays.asList(str.split(",")); //[a, b, c]
            //List集合转换String
            String radioAnswerStr = String.join (",", radioAnswer);
            userAnswer.setRadioAnswer (radioAnswerStr);
        }

        //多选题计算
        if (CollUtil.isNotEmpty (testExamAnswerVo.getMultiList ())) {
            List<QuestionIdAndAnswer> multiList = testExamAnswerVo.getMultiList ();
            List<String> multiList2 = new ArrayList<> ();
            for (QuestionIdAndAnswer questionIdAndAnswer : multiList) {
                ExamQuestion examQuestion = questionMapper.selectById (questionIdAndAnswer.getQuestionId ());
                List<String> andAnswerList2 = questionIdAndAnswer.getAndAnswerList ();
                String radioAnswerStr = String.join (",", andAnswerList2);
                String questA = questionIdAndAnswer.getQuestionId () + "-" + radioAnswerStr;
                multiList2.add (questA);
                String selectAnswer = examQuestion.getSelectAnswer ();
                List<String> andAnswerList = questionIdAndAnswer.getAndAnswerList ();
                List<String> list1 = Arrays.asList (selectAnswer.split (","));
                if (andAnswerList.size () == list1.size () && andAnswerList.containsAll (list1)) {
                    subjectiveScore += paper.getMultiScore ();
                }
            }
            String multiAnswerStr = String.join ("/", multiList2);
            userAnswer.setMultiAnswer (multiAnswerStr);
        }


        //判断题计算
        if (CollUtil.isNotEmpty (testExamAnswerVo.getJudgeList ())) {
            List<String> judgeListStr = new ArrayList<> ();
            List<QuestionIdAndAnswer> judgeList = testExamAnswerVo.getJudgeList ();
            for (QuestionIdAndAnswer questionIdAndAnswer : judgeList) {
                ExamQuestion examQuestion = questionMapper.selectById (questionIdAndAnswer.getQuestionId ());
                if (examQuestion.getTrueFalse () == Integer.parseInt (questionIdAndAnswer.getAnswer ())) {
                    subjectiveScore += paper.getJudgeScore ();
                }
                String str = questionIdAndAnswer.getQuestionId () + "-" + questionIdAndAnswer.getAnswer ();
                judgeListStr.add (str);
            }

            String judgeStr = String.join (",", judgeListStr);
            userAnswer.setJudgeAnswer (judgeStr);
        }

        Integer objectiveScore = 0;
        //简答题计算
        if (paper.getShortAnswerNum () != 0) {

            if (CollUtil.isNotEmpty (testExamAnswerVo.getShortAnswerList ())) {
                List<String> shortStr = new ArrayList<> ();
                List<QuestionIdAndAnswer> shortAnswerList = testExamAnswerVo.getShortAnswerList ();

                Boolean isMark = true;
                for (QuestionIdAndAnswer questionIdAndAnswer : shortAnswerList) {
                    if (StrUtil.isBlank (questionIdAndAnswer.getAnswer ())) {
                        //未作答
                        continue;
                    } else {
                        isMark = false;
                        String s = questionIdAndAnswer.getQuestionId () + "-" + questionIdAndAnswer.getAnswer ();
                        shortStr.add (s);
                        //userAnswer.setIsMarkSub (3);
                    }
                }

                if (!isMark) {
                    //需要评分
                    userAnswer.setTotalScore (objectiveScore + subjectiveScore);
                    userAnswer.setIsMarkSub (3);
                } else {
                    //无需评分
                    userAnswer.setObjectiveScore (objectiveScore);
                    userAnswer.setTotalScore (objectiveScore + subjectiveScore);
                    userAnswer.setIsMarkSub (2);
                }

                String join = String.join ("//", shortStr);
                userAnswer.setShortAnswer (join);
            } else {
                //未作答
                userAnswer.setObjectiveScore (objectiveScore);
                userAnswer.setTotalScore (objectiveScore + subjectiveScore);
                userAnswer.setIsMarkSub (2);
            }
            //未评分
            //userAnswer.setIsMarkSub (3);
        } else {
            //无需评分
            userAnswer.setTotalScore (objectiveScore + subjectiveScore);
            userAnswer.setObjectiveScore (objectiveScore);
            userAnswer.setIsMarkSub (2);
        }

        userAnswer.setSubjectiveScore (subjectiveScore);

        userAnswerMapper.insert (userAnswer);
        return ResponseBean.success ("交卷成功");
    }

    public ResponseBean findPage(PageVo pageVo, Long paperId, HttpSession session) {

        QueryWrapper<UserAnswer> wrapper = new QueryWrapper<> ();
        Page<UserAnswer> page = new Page<> (pageVo.getCurrentPage (), pageVo.getPageSize ());

        wrapper.eq ("paper_id", paperId);

        if (StrUtil.isNotBlank (pageVo.getQueryContent ())) {
            List userId = userMapper.selectIdLikeRealName (pageVo.getQueryContent ());
            if (CollUtil.isEmpty (userId)) {
                wrapper.eq ("user_id", 0);
            } else {
                wrapper.in ("user_id", userId);
            }
        }


        IPage<UserAnswer> userAnswerIPage = userAnswerMapper.selectPage (page, wrapper);

        PageVo pv = new PageVo ();

        pv.setTotal (userAnswerIPage.getTotal ());

        List<UserAnswer> userAnswerList = userAnswerIPage.getRecords ();

        for (UserAnswer userAnswer : userAnswerList) {
            User user = userMapper.selectById (userAnswer.getUserId ());
            userAnswer.setUser (user);
        }

        pv.setData (userAnswerList);

        return ResponseBean.success (ContentBean.QuerySuccess, pv);
    }

    public ResponseBean findDetail(Long paperId, Integer userId, HttpSession session) {

        QueryWrapper<UserAnswer> userAnswerQueryWrapper = new QueryWrapper<> ();
        userAnswerQueryWrapper.eq ("user_id", userId).eq ("paper_id", paperId);
        //答题记录
        UserAnswer userAnswer = userAnswerMapper.selectOne (userAnswerQueryWrapper);

        String radioAnswer = userAnswer.getRadioAnswer ();
        //单选题用户答案
        List<String> radioList = new ArrayList<> ();
        if (StrUtil.isNotBlank (radioAnswer)){
            List<String> list = Arrays.asList (radioAnswer.split (","));
            radioList.addAll (list);
        }


        String multiAnswer = userAnswer.getMultiAnswer ();
        //多选题用户答案
        List<String> multiList = new ArrayList<> ();
        if (StrUtil.isNotBlank (multiAnswer)){
            List<String> list = Arrays.asList (multiAnswer.split ("/"));
            multiList.addAll (list);
        }


        String judgeAnswer = userAnswer.getJudgeAnswer ();
        //判断题用户答案
        List<String> judgeList = new ArrayList<> ();
        if (StrUtil.isNotBlank (judgeAnswer)){
            List<String> list = Arrays.asList (judgeAnswer.split (","));
            judgeList.addAll (list);
        }

        String shortAnswer = userAnswer.getShortAnswer ();
        //简答题用户答案
        List<String> shortList = new ArrayList<> ();
        if (StrUtil.isNotBlank (shortAnswer)){
            List<String> list = Arrays.asList (shortAnswer.split ("//"));
            shortList.addAll (list);
        }

        //答题试卷
        Paper paper = paperMapper.selectById (paperId);

        QueryWrapper<ExamQuestion> questionQueryWrapper = new QueryWrapper<> ();
        questionQueryWrapper.orderByAsc ("question_type");

        List<ExamQuestion> examQuestions = null;
        //随机卷
        if (paper.getPaperType () == 1) {
            Map map = new HashMap ();
            map.put ("paperId", paperId);
            map.put ("userId", userId);
            List<Long> questionIds = randomPaperQuestionMapper.queryQuestionIdByPaperIdAndUserId (map);
            questionQueryWrapper.in ("id", questionIds);
            examQuestions = questionMapper.selectList (questionQueryWrapper);
        } else {
            //手动卷
            List<Long> questionIds = manualPaperQuestionMapper.queryQuestionIdByPaperId (paperId);
            questionQueryWrapper.in ("id", questionIds);
            examQuestions = questionMapper.selectList (questionQueryWrapper);
        }

        //返回的结果
        List<UserAnswerDetail> userAnswerDetailList = new ArrayList<> ();
        if (CollUtil.isNotEmpty (examQuestions)) {
            for (ExamQuestion examQuestion : examQuestions) {
                UserAnswerDetail userAnswerDetail = new UserAnswerDetail ();
                userAnswerDetail.setUserAnswerBean (userAnswer);
                userAnswerDetail.setPaper (paper);
                userAnswerDetail.setExamQuestion (examQuestion);
                if (examQuestion.getQuestionType () == 1) {

                    if (CollUtil.isNotEmpty (radioList)) {
                        for (String r : radioList) {
                            String[] rp = r.split ("-");
                            if (Long.parseLong (rp[0]) == examQuestion.getId ()) {
                                userAnswerDetail.setUserAnswer (rp[1]);
                                if ((examQuestion.getRadioAnswer ()).equals (rp[1])) {
                                    userAnswerDetail.setScore (paper.getRadioScore ());
                                } else {
                                    userAnswerDetail.setScore (0);
                                }

                            }
                        }
                    } else {
                        userAnswerDetail.setUserAnswer ("");
                        userAnswerDetail.setScore (0);
                    }
                    userAnswerDetail.setQuestionScore (paper.getRadioScore ());
                    userAnswerDetail.setQuestionAnswer (examQuestion.getRadioAnswer ());
                } else if (examQuestion.getQuestionType () == 2) {

                    if (CollUtil.isNotEmpty (multiList)) {
                        for (String m : multiList) {
                            String[] mp = m.split ("-");
                            if (Long.parseLong (mp[0]) == examQuestion.getId ()) {
                                userAnswerDetail.setUserAnswer (mp[1]);

                                List<String> mus = Arrays.asList ((examQuestion.getSelectAnswer ()).split (",")); //[a, b, c]
                                //Collections.sort (mus);
                                List<String> list = Arrays.asList (mp[1].split (","));
                                if (mus.size () == list.size () && mus.containsAll (list)) {
                                    userAnswerDetail.setScore (paper.getMultiScore ());
                                } else {
                                    userAnswerDetail.setScore (0);
                                }

                            }
                        }
                    } else {
                        userAnswerDetail.setUserAnswer ("");
                        userAnswerDetail.setScore (0);
                    }
                    userAnswerDetail.setQuestionScore (paper.getMultiScore ());
                    userAnswerDetail.setQuestionAnswer (examQuestion.getSelectAnswer ());
                } else if (examQuestion.getQuestionType () == 3) {
                    if (CollUtil.isNotEmpty (judgeList)) {
                        for (String jp : judgeList) {
                            String[] jm = jp.split ("-");
                            if (Long.parseLong (jm[0]) == examQuestion.getId ()) {
                                userAnswerDetail.setUserAnswer (jm[1]);

                                if (examQuestion.getTrueFalse () == Integer.parseInt (jm[1])) {
                                    userAnswerDetail.setScore (paper.getJudgeScore ());
                                } else {
                                    userAnswerDetail.setScore (0);
                                }

                            }
                        }
                    } else {
                        userAnswerDetail.setUserAnswer ("");
                        userAnswerDetail.setScore (0);
                    }
                    userAnswerDetail.setQuestionScore (paper.getJudgeScore ());
                    userAnswerDetail.setQuestionAnswer (String.valueOf (examQuestion.getTrueFalse ()));
                } else {
                    if (CollUtil.isNotEmpty (shortList)) {
                        String answerObjScore = userAnswer.getObjScore ();
                        for (String sp : shortList) {
                            String[] sm = sp.split ("-");
                            if (Long.parseLong (sm[0]) == examQuestion.getId ()) {
                                userAnswerDetail.setUserAnswer (sm[1]);
                            }

                            if (StrUtil.isBlank (answerObjScore)){
                                userAnswerDetail.setShortScore (0);
                            } else {
                                List<String> list = Arrays.asList (answerObjScore.split (","));
                                for (String s : list) {
                                    String[] shm = s.split ("-");
                                    if (Long.parseLong (shm[0])==examQuestion.getId ()){
                                        userAnswerDetail.setShortScore (1);
                                        userAnswerDetail.setScore (Integer.parseInt (shm[1]));
                                    }
                                }
                            }
                        }
                    } else {
                        userAnswerDetail.setUserAnswer ("");
                        userAnswerDetail.setScore (0);
                    }
                    userAnswerDetail.setQuestionScore (paper.getJudgeScore ());
                }

                userAnswerDetailList.add (userAnswerDetail);
            }

            return ResponseBean.success (ContentBean.QuerySuccess, userAnswerDetailList);
        }

        return ResponseBean.error ("系统错误!");


    }

    public ResponseBean reviewScore(Long paperId, Integer userId, Integer score, Long questionId, HttpSession session) {
        QueryWrapper<UserAnswer> userAnswerQueryWrapper = new QueryWrapper<> ();
        userAnswerQueryWrapper.eq ("user_id",userId).eq ("paper_id",paperId);


        UserAnswer userAnswer = userAnswerMapper.selectOne (userAnswerQueryWrapper);

        //Paper paper = paperMapper.selectById (paperId);


        String obj = questionId+"-"+score;

        String objScore = userAnswer.getObjScore ();

        List<String> quesA = new ArrayList<> ();
        if (StrUtil.isBlank (objScore)){
            quesA.add (obj);
        } else {
            List<String> list = Arrays.asList (objScore.split (","));
            quesA.addAll (list);
            quesA.add (obj);
        }

        List<String> sps = new ArrayList<> ();
        for (String s : quesA) {
            String[] split = s.split ("-");
            sps.add (split[0]);
        }

        String objScores = String.join (",", quesA);
        userAnswer.setObjScore (objScores);

        String shortAnswer = userAnswer.getShortAnswer ();
        List<String> shortList = Arrays.asList (shortAnswer.split ("//"));

        List<String> sp = new ArrayList<> ();
        for (String sh : shortList) {
            String[] split = sh.split ("-");
            sp.add (split[0]);
        }

        if (sps.size ()==sp.size ()&&sps.containsAll (sp)){
            userAnswer.setIsMarkSub (1);
        }

        userAnswer.setObjectiveScore (userAnswer.getObjectiveScore ()+score);

        userAnswerMapper.updateById (userAnswer);

        return ResponseBean.success (ContentBean.UpdateSuccess);
    }
}
